package cn.turboinfo.fuyang.api.domain.scheduler.usecase.profit

import cn.turboinfo.fuyang.api.domain.common.service.account.CompanyAccountService
import cn.turboinfo.fuyang.api.domain.common.service.custom.ServiceCustomService
import cn.turboinfo.fuyang.api.domain.common.service.order.PayOrderService
import cn.turboinfo.fuyang.api.domain.common.service.profit.ProfitSharingService
import cn.turboinfo.fuyang.api.domain.common.service.wechat.WechatPayService
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase
import cn.turboinfo.fuyang.api.entity.common.enumeration.account.AccountType
import cn.turboinfo.fuyang.api.entity.common.enumeration.common.EntityObjectType
import cn.turboinfo.fuyang.api.entity.common.enumeration.custom.ServiceCustomStatus
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.PayOrderStatus
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.PayType
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.ServiceOrderRefundStatus
import cn.turboinfo.fuyang.api.entity.common.enumeration.profit.ProfitSharingStatus
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.QServiceCustom
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.ServiceCustomUpdater
import cn.turboinfo.fuyang.api.entity.common.pojo.profit.ProfitSharingCreator
import net.sunshow.toolkit.core.qbean.api.request.QPage
import net.sunshow.toolkit.core.qbean.api.request.QRequest
import net.sunshow.toolkit.core.qbean.helper.component.request.QPageRequestHelper
import org.apache.commons.lang3.StringUtils
import org.springframework.stereotype.Component
import java.math.BigDecimal
import java.math.MathContext
import java.time.LocalDate

@Component
class SchedulerServiceCustomProfitSharingUseCase(
    private val wechatPayService: WechatPayService,
    private val serviceCustomService: ServiceCustomService,
    private val payService: PayOrderService,
    private val companyAccountService: CompanyAccountService,
    private val profitSharingService: ProfitSharingService,
) : AbstractUseCase<SchedulerServiceCustomProfitSharingUseCase.InputData, SchedulerServiceCustomProfitSharingUseCase.OutputData>() {

    override fun doAction(input: InputData): OutputData {

        val now = LocalDate.now()

        val request = QRequest.newInstance()
            .filterEqual(QServiceCustom.refundStatus, ServiceOrderRefundStatus.INIT)
            .filterEqual(QServiceCustom.customStatus, ServiceCustomStatus.COMPLETED)
            .filterEqual(QServiceCustom.profitSharingStatus, ProfitSharingStatus.INIT)
            // 查询一周前完成的订单
            .filterLessThan(QServiceCustom.completedTime, now.minusWeeks(1).atTime(0, 0, 0))

        val requestPage = QPage.newInstance()
            .paging(0, 100)

        QPageRequestHelper.request(request, requestPage, serviceCustomService::findAll)
            .onEach {

                try {
                    // 查询支付订单
                    val payOrderList =
                        payService.findByObjectIdAndStatus(EntityObjectType.SERVICE_CUSTOM, it.id, PayOrderStatus.PAID)
                            .filter { payOrder -> payOrder.payType.equals(PayType.WECHAT) }

                    for (payOrder in payOrderList) {
                        // 创建分账订单
                        val builder = ProfitSharingCreator
                            .builder()
                            .withObjectId(it.id)
                            .withObjectType(EntityObjectType.SERVICE_CUSTOM)
                            .withCompanyId(it.companyId)
                            .withWxTransactionId(payOrder.transactionId)
                            .withWxOrderId(StringUtils.EMPTY)
                            .withStatus(ProfitSharingStatus.INIT)

                        val profitSharing = profitSharingService.save(builder.build())

                        // 查询企业账户
                        val companyAccount = companyAccountService.findByCompanyId(profitSharing.companyId)
                            .stream()
                            .findFirst()
                            .orElseThrow { RuntimeException("企业账户不存在") }

                        // 发起分账
                        wechatPayService.applyProfitsharing(
                            payOrder.transactionId,
                            profitSharing.id,
                            payOrder.amount.multiply(BigDecimal(100), MathContext.UNLIMITED).toLong(),
                            companyAccount.account,
                            companyAccount.name,
                            AccountType.get(companyAccount.type.value).code,
                            "定制服务 -" + it.contact + "-分账",
                        )
                    }

                    // 更新服务订单分账状态
                    serviceCustomService.update(
                        ServiceCustomUpdater.builder(it.id)
                            .withProfitSharingStatus(ProfitSharingStatus.PROCESSING)
                            .build()
                    )
                } catch (e: Exception) {
                    logger.error("分账失败, 订单编码： {} ", it.id, e)
                }

            }
        return OutputData()
    }

    class InputData : AbstractUseCase.InputData()

    class OutputData : AbstractUseCase.OutputData()

}
